<template>
<div>
  <el-dialog
    :title="!dataForm.id ? '新增' : (reportLayer ? '反馈':'修改')"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form v-loading="formLoading" :model="dataForm" inline :rules="dataRule"  ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px">

    
      <el-form-item v-if="!reportLayer" label="所属基地"  prop="deptId">
          <el-input v-if="!reportLayer" v-model="dataForm.deptName" v-popover:deptListPopover  readonly=""  v- placeholder="所属基地"></el-input> 
          
          <!-- <el-tooltip v-if="!reportLayer" class="item" style="width:10%;" effect="dark" content="更换基地将会清除田块" placement="top-start">
          <el-button>*</el-button>
         </el-tooltip> -->

            <el-popover v-if="!reportLayer" ref="deptListPopover" placement="bottom-start"  @hide="hidep()" trigger="click">
              <el-tree v-if="!reportLayer"
                ref="deptListTree" node-key="id" 
                show-checkbox
                :data="deptList" 
                :props="deptListTreeProps"
                @check-change="checkChange"
                :check-strictly="true" 
                :default-expand-all="true"
                :highlight-current="true" 
                :expand-on-click-node="false"
              >
              </el-tree>
          </el-popover>
        </el-form-item>
  

    <el-form-item v-if="!reportLayer" label="巡检田块" prop="farmlandInfoIds">
          <div v-if="!reportLayer" @click="changeInput">
            <el-input v-model="farmlandInfoIdsname" readonly=""  placeholder="巡检田块"></el-input>
          </div>
    </el-form-item>

    
       

          <!-- <el-form-item  v-if="!reportLayer" label="巡检计划" prop="inspectionPlanId">
        <el-select v-if="!reportLayer"
            v-model="dataForm.inspectionPlanId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键字"
            :remote-method="remoteMethod"
            :loading="handlerListLoading2"
            v-loadmore="handlerListLoadMore2">
            <el-option
            v-for="item in handlerList2"
            :key="item.id"
            :label="item.name"
            :value="item.id">
            </el-option>
        </el-select>
    </el-form-item> -->

    
    <el-form-item v-if="!reportLayer" label="巡检任务名称" prop="taskName">
      <el-input v-model="dataForm.taskName" placeholder="巡检任务名称"></el-input>
    </el-form-item>
    <el-form-item v-if="!reportLayer" label="巡检人" prop="handler">
        <el-select class="form-item"  v-if="!reportLayer"
            v-model="dataForm.handler"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键字"
            :remote-method="remoteMethod"
            :loading="handlerListLoading"
            v-loadmore="handlerListLoadMore">
            <el-option
            v-for="item in handlerList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
            </el-option>
        </el-select>
    </el-form-item>

   
    <el-form-item v-if="!reportLayer" label="巡检计划时间" prop="startTime">
      <!-- <el-input v-model="dataForm.startTime" placeholder="巡检开始时间"></el-input> -->
          <el-date-picker v-if="!reportLayer"
                          class="form-item"
            v-model="dataForm.startTime"
            type="datetime"
            placeholder="巡检计划时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            >
          </el-date-picker>

    </el-form-item>
    <el-form-item v-if="!reportLayer" label="巡检任务内容" prop="taskContent">
      <el-input type="textarea" :rows="3" style="width:500px" v-model="dataForm.taskContent" placeholder="巡检任务内容"></el-input>
    </el-form-item>

    <!-- <el-form-item v-if="reportLayer" label="巡检结果状态 " placeholder="请选择" prop="resultStatus">
      <el-select class="form-item" v-if="reportLayer" v-model="dataForm.resultStatus" placeholder="请选择" >
           <el-option
            v-for="item in statusoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>

    </el-form-item> -->
    <el-form-item v-if="reportLayer" label="巡检结果状态" prop="resultStatus">
      <el-radio-group v-model="dataForm.resultStatus" >
          <el-radio v-for="item in statusoptions" :key="item.value" :label="item.value">{{item.label}}</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item v-if="reportLayer" label="巡检结果描述" prop="resultContent">
      <el-input type="textarea" :rows="3" style="width:500px" v-if="reportLayer" v-model="dataForm.resultContent" placeholder="巡检结果描述"></el-input>
    </el-form-item>
    <!-- <el-form-item v-if="reportLayer" label="状态： " prop="status" placeholder="请选择">
      <el-select class="form-item" v-if="reportLayer" v-model="dataForm.status" placeholder="请选择">
          <el-option
            v-for="item in ztoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
    </el-form-item> -->
    <!-- <el-form-item v-if="reportLayer" label="来源类型 " prop="sourceType" placeholder="请选择">
     
       <el-select class="form-item" v-if="reportLayer" v-model="dataForm.sourceType" placeholder="请选择">
          <el-option
            v-for="item in lylxoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>

        </el-select>
    </el-form-item> -->
    <!-- <el-form-item v-if="reportLayer" label="计划时间" prop="planTime">
          <el-date-picker
            class="form-item"
            v-model="dataForm.planTime"
            type="datetime"
            placeholder="计划时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            >
          </el-date-picker>
    </el-form-item> -->
      <el-form-item v-if="reportLayer" label="巡检附件ids" prop="resultFileIds">
    
      <multipleFileUpload ref="multipleFileUploadRef"></multipleFileUpload>
    </el-form-item>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button v-loading="formLoading" type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
 
     <bussfarmlandinfoSelect v-if="bussfarmlandinfoSelectVisible" ref="bussfarmlandinfoSelect"
        @bussFarmlandInfoSelectChange="bussFarmlandInfoSelectChange"></bussfarmlandinfoSelect>
</div>
</template>

<script>
import multipleFileUpload from '@/components/multiple-flie-upload/index'
 import { treeDataTranslate } from '@/utils'
 import bussfarmlandinfoSelect from './bussfarmlandinfoSelect'
  export default {
    components: {
      multipleFileUpload,
      bussfarmlandinfoSelect
    },
    data () {
      return {
        visible: false,
        formLoading: false,
         demoVisible: false,
        reportLayer:false,
        bussfarmlandinfoSelectVisible:false,
        farmlandInfoIdsname:'',
        dataForm: {
          id: 0,
          farmlandInfoIds: '',
          resultFileIds: '',
          parentName:'',
          handler: '',
          inspectionPlanId: '',
           deptId: '',
          deptName:'',
          businessNum: '',
          taskName: '',
          taskContent: '',
          startTime: '',
          planTime: '',
          resultStatus: '',
          resultContent: '',
          status: '',
          sourceType: '',
          createId: '',
          createName: '',
          createTime: '',
          updateId: '',
          updateTime: '',
          updateName: '',
          version: '',
          gcFlag: '',
          planTime: '',

        },
          statusoptions: [{
          value: Number('0'),
          label: '一切正常'
        }, {
          value: Number('1'),
          label: '存在异常'
        }],
        ztoptions: [{
          value: Number('0'),
          label: '待处理'
        }, {
          value: Number('1'),
          label: '进行中'
        }, {
          value: Number('2'),
          label: '已处理'
        }],
         lylxoptions: [{
          value: Number('0'),
          label: '主动添加'
        }, {
          value: Number('1'),
          label: '计划添加'
        }],
        dataRule: {
          resultFileIds: [
           // { required: true, message: '巡检附件ids不能为空', trigger: 'blur' }
          ],
          farmlandInfoIds: [
            { required: true, message: '巡检田块不能为空', trigger: 'change' }
          ],
          handler: [
            { required: true, message: '巡检人不能为空', trigger: 'blur' }
          ],
          inspectionPlanId: [
            { required: true, message: '巡检人不能为空', trigger: 'blur' }
          ],
          deptId: [
            { required: true, message: '所属基地不能为空', trigger: 'change' }
          ],
         
          taskName: [
            { required: true, message: '巡检任务名称不能为空', trigger: 'blur' }
          ],
          taskContent: [
            { required: true, message: '巡检任务内容不能为空', trigger: 'blur' }
          ],
          startTime: [
            { required: true, message: '巡检开始时间不能为空', trigger: 'blur' }
          ],
          // finishTime: [
          //   { required: true, message: '巡检完成时间不能为空', trigger: 'blur' }
          // ],
          resultStatus: [
            { required: true, message: '巡检结果状态 不能为空', trigger: 'blur' }
          ],
          // resultContent: [
          //   { required: true, message: '巡检结果描述不能为空', trigger: 'blur' }
          // ],
  
        },
         menuList: [],
         multipleSelection: [],
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        key: '',
        handlerListLoading:false,
        handlerList:[],// 处理人列表
        hadlerParams:{},// 处理人查询参数
        gjjbList:[],
        handlerListLoading2:false,
         deptList: [],
        deptListTreeProps: {
          label: 'name',
          children: 'children',
          disabled: function(data, node){
            return data.type == 1 ? false :true
          }
        },
        handlerList2:[],// 处理人列表
        hadlerParams2:{},// 处理人查询参数

        menuListTreeProps: {
          // label: 'name',
          // children: 'children'
          label: 'name',
          children: 'children',
          disabled: function(data, node){
            return data.type == 1 ? false :true
          }
        },
        oldvalue:'',
      }
    },
    methods: {
      init (id,zt) {
        this.dataForm.deptId = ''
        this.dataForm.deptName = ''
         // 加载负责人下拉框
        this.handlerListLoadMore('init')
         this.handlerListLoadMore2('init')
         
        if(zt == 'xg'){
          this.reportLayer = false;
        }else if(zt == 'fk'){
          this.reportLayer = true;
         
        }else{
           this.reportLayer = false;
        }

        

        this.dataForm.id = id || 0
        this.$http({
          url: this.$http.adornUrl('/sys/dept/select2'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {

          this.deptList = treeDataTranslate(data.deptList, 'id')
        }).then(() => {
          this.visible = true
          this.formLoading = false
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
            this.farmlandInfoIdsname = ""
          })
          }).then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/buss/bussinspectiontask/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.resultFileIds = data.bussInspectionTask.resultFileIds
                this.dataForm.farmlandInfoIds = data.bussInspectionTask.farmlandInfoIds
                this.dataForm.handler = data.bussInspectionTask.handler
                this.dataForm.inspectionPlanId = data.bussInspectionTask.inspectionPlanId
                this.dataForm.deptId = data.bussInspectionTask.deptId
                this.dataForm.businessNum = data.bussInspectionTask.businessNum
                this.dataForm.taskName = data.bussInspectionTask.taskName
                this.dataForm.taskContent = data.bussInspectionTask.taskContent
                this.dataForm.startTime = data.bussInspectionTask.startTime
                this.dataForm.planTime = data.bussInspectionTask.planTime
                this.dataForm.resultStatus = data.bussInspectionTask.resultStatus
                this.dataForm.resultContent = data.bussInspectionTask.resultContent
                this.dataForm.status = data.bussInspectionTask.status
                this.dataForm.sourceType = data.bussInspectionTask.sourceType
                this.dataForm.createId = data.bussInspectionTask.createId
                this.dataForm.createName = data.bussInspectionTask.createName
                this.dataForm.createTime = data.bussInspectionTask.createTime
                this.dataForm.updateId = data.bussInspectionTask.updateId
                this.dataForm.updateTime = data.bussInspectionTask.updateTime
                this.dataForm.updateName = data.bussInspectionTask.updateName
                this.dataForm.version = data.bussInspectionTask.version
                this.dataForm.gcFlag = data.bussInspectionTask.gcFlag
                this.dataForm.planTime = data.bussInspectionTask.planTime
                this.farmlandInfoIdsname = data.bussInspectionTask.farmlandInfoIdsname
                 this.oldvalue = data.bussInspectionTask.deptId
                this.deptListTreeSetCurrentNode()
                
              }
            })
          }
        })
      },
      tkinfo () {

      },
      finishInit(id){
          this.dataForm.id = id || 0

          this.visible = true
          this.formLoading = false
          this.dataForm.status = 2
          this.$nextTick(() => {
            // 清除上传缓存
            this.$refs['multipleFileUploadRef'].clearHistory()
            this.$refs['dataForm'].resetFields()
          })
      },
       changeInput() {
        // this.demoVisible = true
        //  if (this.multipleSelection.length == 0) {
        //    this.search()
        //  }
        if(this.dataForm.deptId == null||this.dataForm.deptId==''){
           alert('请先选择基地');
           return;
        }
         this.bussfarmlandinfoSelectVisible =true
        this.$nextTick(() => {
          this.$refs.bussfarmlandinfoSelect.init(this.dataForm.farmlandInfoIds,this.dataForm.deptId)
        })
      },
       bussFarmlandInfoSelectChange(ids,names){
          this.dataForm.farmlandInfoIds = ids
          this.farmlandInfoIdsname = names
      },
      handleSelectionChange(val) {
        console.log('%c------------ 验证是否每次都调用', 'color:green')
        console.log(val)
        this.multipleSelection = val
        let list = []
        val.forEach(x => {
          list.push(x.id)
        })
        this.dataForm.farmlandInfoIds = list.join(',')
      },
      //  search() {
      //   this.$http({
      //     url: this.$http.adornUrl('/buss/bussfarmlandinfo/list'),
      //     method: 'get',
      //     params: this.$http.adornParams({
      //       'page': this.pageIndex,
      //       'limit': this.pageSize,
      //       'key': this.key,
      //       'jd':this.dataForm.deptId
      //     })
      //   }).then(({data}) => {
      //     if (data && data.code === 0) {
      //       if (this.multipleSelection.length > 0) {
      //         this.multipleSelection.forEach(x => {
      //           data.page.list.forEach((y, index) => {
      //               if (x.id == y.id) {
      //                 this.$refs.multipleTable.toggleRowSelection(data.page.list[index], true)
      //               }
      //           })
      //         })
      //       }
      //       this.dataList = data.page.list
      //       this.totalPage = data.page.totalCount
      //     } else {
      //       this.dataList = []
      //       this.totalPage = 0
      //     }
      //     this.dataListLoading = false
      //   })
      // },
      // 菜单树选中
      // menuListTreeCurrentChangeHandle (data, node) {
      //   debugger;
      //    if(this.dataForm.deptId!=null&&this.dataForm.deptId!=''){
      //    this.$confirm('更换基地将清除田块')
      //     .then(_ => {
      //      // done();
      //      this.dataForm.farmlandInfoIds = ''
      //       this.farmlandInfoIdsname = ''
      //        this.dataForm.deptId = data.id
      //   this.dataForm.parentName = data.name
      //     })
      //     .catch(_ => {
      //       debugger;
      //       return;

      //     });
      //   }else{
      //   this.dataForm.deptId = data.id
      //   this.dataForm.parentName = data.name
      //   }
       
        
      //   //选中触发搜索
      //   this.search();
      // },
      // 菜单树设置当前选中节点
      deptListTreeSetCurrentNode () {
        this.$refs.deptListTree.setChecked(this.dataForm.deptId,true,false)
        this.dataForm.deptName = (this.$refs.deptListTree.getCheckedNodes() || [])[0].name
      },
     // 节点修改
      checkChange(data, checked, node){
        if(checked == true){// 选中部门
          //  this.dataForm.farmlandInfoIds = ''
          //  this.farmlandInfoIdsname = ''
            this.checkedId = data.id
            this.$refs.deptListTree.setCheckedNodes([data])
             this.dataForm.deptId = data.id
             this.dataForm.deptName = data.name
          }

      },

      hidep () {
         debugger
         if(this.dataForm.deptId == ''){
         // this.oldvalue = this.dataForm.deptId
        }else
        if( this.oldvalue != this.dataForm.deptId && this.oldvalue != ''){

          this.$confirm('更换基地将清除田块')
            .then(_ => {
        
               this.dataForm.farmlandInfoIds = ''
               this.dataForm.farmlandInfoIdsname = ''
               this.oldvalue = this.dataForm.deptId
               this.checki()
          
          })
          .catch(_ => {
            this.dataForm.deptId = this.oldvalue;
            //return;
            this.checki()

          });
         
          }else if(this.oldvalue == ''){
             this.dataForm.farmlandInfoIds = ''
               this.dataForm.farmlandInfoIdsname = ''
               this.oldvalue = this.dataForm.deptId
               this.checki()
            
          } 
        
          
          
      },
      checki(){
        this.checkedId = this.dataForm.deptId;
        var b = this.$refs.deptListTree.getCheckedNodes(this.checkedId)
        this.$refs.deptListTree.setCheckedNodes([b])
        this.deptListTreeSetCurrentNode();
      },
      // 图标选中
      iconActiveHandle (iconName) {
        this.dataForm.icon = iconName
      },
      // 接收工单
      receive(id){
        this.dataForm.id = id || 0
        this.$confirm(`确认接收该任务吗，接收后不可退回？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
              url: this.$http.adornUrl(`/buss/bussinspectiontask/update`),
              method: 'post',
              data: this.$http.adornData({
              'id': this.dataForm.id || undefined,
              'status': 1,
              })
          }).then(({data}) => {
              if (data && data.code === 0) {
                  this.$message({
                      message: '操作成功',
                      type: 'success',
                      duration: 1500,
                      onClose: () => {
                      this.visible = false
                      this.$emit('refreshDataList')
                      }
                  })
              } else {
                  this.$message.error(data.msg)
              }
          })
        })
      },
      // 表单提交
      dataFormSubmit () {
        debugger;
        if(this.reportLayer == true){
         this.dataForm.status = '2'
        }

        var uploadFileIds = this.$cookie.get('uploadFileIds')

        this.$refs['dataForm'].validate((valid) => {
          if (valid && !this.formLoading) {
            this.formLoading = true
            this.$http({
              url: this.$http.adornUrl(`/buss/bussinspectiontask/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'resultFileIds': uploadFileIds,
                'farmlandInfoIds': this.dataForm.farmlandInfoIds,
                'handler': this.dataForm.handler,
                'inspectionPlanId': this.dataForm.inspectionPlanId,
                'deptId': this.dataForm.deptId,
                'businessNum': this.dataForm.businessNum,
                'taskName': this.dataForm.taskName,
                'taskContent': this.dataForm.taskContent,
                'startTime': this.dataForm.startTime,
                'planTime': this.dataForm.planTime,
                'resultStatus': this.dataForm.resultStatus,
                'resultContent': this.dataForm.resultContent,
                'status': this.dataForm.status,
                'sourceType': this.dataForm.sourceType,
                'createId': this.dataForm.createId,
                'createName': this.dataForm.createName,
                'createTime': this.dataForm.createTime,
                'updateId': this.dataForm.updateId,
                'updateTime': this.dataForm.updateTime,
                'updateName': this.dataForm.updateName,
                'version': this.dataForm.version,
                'gcFlag': this.dataForm.gcFlag,
                'planTime': this.dataForm.planTime
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.formLoading = false
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
        // 这里下拉框查询触发的方法
      remoteMethod(query) {
        this.handlerListLoadMore('query',query)
      },
      // 这里写入滚动加载要触发的方法
      handlerListLoadMore (type,query) {
        this.handlerListLoading = true

        if(type && (type == 'init' || type == 'query')){
            this.hadlerParams.page = 1
            this.handlerList = []
        }else if(this.hadlerParams.page){
            if(this.hadlerParams.page>=this.hadlerParams.totalPage){
                this.handlerListLoading = false
                return
            }
            this.hadlerParams.page += 1
        }
        
        var _this = this
        this.$http({
            url: this.$http.adornUrl('/sys/user/list2'),
            method: 'get',
            params: this.$http.adornParams({
                "name": query, //搜索参数
                "page": _this.hadlerParams.page || 1, //分页参数
                "limit": _this.hadlerParams.limit || 15, //每次查询15条记录
            })
        }).then(({data}) => {
            _this.handlerListLoading = false
            _this.hadlerParams.totalPage = data.page.totalPage
            _this.handlerList = _this.handlerList.concat(data.page.list)
        })
      },
       // 这里下拉框查询触发的方法
      remoteMethod2(query) {
        this.handlerListLoadMore2('query',query)
      },
      // 这里写入滚动加载要触发的方法
      handlerListLoadMore2 (type,query) {
        this.handlerListLoading2 = true

        if(type && (type == 'init' || type == 'query')){
            this.hadlerParams2.page = 1
            this.handlerList2 = []
        }else if(this.hadlerParams2.page){
            if(this.hadlerParams2.page>=this.hadlerParams2.totalPage){
                this.handlerListLoading2 = false
                return
            }
            this.hadlerParams2.page += 1
        }
        
        var _this = this
        this.$http({
            url: this.$http.adornUrl('/buss/bussinspectionplan/list'),
            method: 'get',
            params: this.$http.adornParams({
                "name": query, //搜索参数
                "page": _this.hadlerParams2.page || 1, //分页参数
                "limit": _this.hadlerParams2.limit || 15, //每次查询15条记录
            })
        }).then(({data}) => {
            _this.handlerListLoading2 = false
            _this.hadlerParams2.totalPage = data.page.totalPage
            _this.handlerList2 = _this.handlerList2.concat(data.page.list)
        })
      }

    }
  }
</script>
